package bupt.com.test.config;

import com.google.gson.GsonBuilder;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import bupt.com.test.BuildConfig;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

/**
 * Created by wyf on 2016/7/18.
 */
public class RetrofitModule {
    private volatile static RetrofitModule instance;
    private OkHttpClient.Builder clientBuilder;
    private Retrofit.Builder retrofitBuilder;
    private HttpLoggingInterceptor loggingInterceptor;//日志拦截器
    private RetrofitModule() {
        initLog();
        initClientBuilder();
        initRetrofitBuilder();
    }

    private void initLog() {
        loggingInterceptor = new HttpLoggingInterceptor();
        if ("debug".equalsIgnoreCase(BuildConfig.BUILD_TYPE)) {
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);
        } else {
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.NONE);
        }
    }

    public static RetrofitModule getInstance() {
        //先检查实例是否存在，如果不存在才进入下面的同步块
        if (instance == null) {
            //同步块，线程安全的创建实例
            synchronized (RetrofitModule.class) {
                //再次检查实例是否存在，如果不存在才真正的创建实例
                if (instance == null) {
                    instance = new RetrofitModule();
                }
            }
        }
        return instance;
    }

    /**
     * 提供实例化的OkHttpClient.Builder对象
     */
    private void initClientBuilder() {
        // 构建OkHttpClient.Builder实例
        clientBuilder = new OkHttpClient.Builder();
        clientBuilder.connectTimeout(Constant.READ_TIMEOUT, TimeUnit.MILLISECONDS);
        clientBuilder.readTimeout(Constant.CONNECT_TIMEOUT, TimeUnit.MILLISECONDS);
        clientBuilder.networkInterceptors().add(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Response originalResponse = chain.proceed(chain.request());
                return originalResponse
                        .newBuilder()
                        .body(new ResBody(originalResponse))
                        .build();
            }
        });
        clientBuilder.addInterceptor(loggingInterceptor);
    }

    private void initRetrofitBuilder() {
        retrofitBuilder = new Retrofit.Builder()
                // 配置baseUrl
                .baseUrl(Constant.HOST_URL)
                // 配置OkHttpClient
                .client(clientBuilder.build())
                //配置返回String类型也能接收
                .addConverterFactory(ScalarsConverterFactory.create())
                // 配置Gson解析
                .addConverterFactory(GsonConverterFactory.create(new GsonBuilder().setDateFormat("yyyy-MM-dd hh:mm:ss").create()));
    }

    /**
     * 根据interface创建Call类型对象
     */
    public <T> T create(Class<T> service) {
        return retrofitBuilder.build().create(service);
    }
}
